package com.zoke.daycarpool.ui;

import java.io.File;
import java.io.FileNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.zoke.daycarpool.R;
import com.zoke.daycarpool.base.BaseUi;
import com.zoke.daycarpool.config.CarpoolParamStore;
import com.zoke.daycarpool.config.CarpoolConfig.PathStores;
import com.zoke.daycarpool.config.CarpoolConfig;
import com.zoke.daycarpool.config.ImageConfig;
import com.zoke.daycarpool.config.UrlBank;
import com.zoke.daycarpool.dialog.AppLoadingDialog;
import com.zoke.daycarpool.domain.UserBeen;
import com.zoke.daycarpool.view.AppDialog;
import com.zoke.daycarpool.view.AppDialog.ChoseItemClick;
import com.zoke.support.config.ZokeConfig;
import com.zoke.support.http.HttpStores;
import com.zoke.support.http.ZokeErro;
import com.zoke.support.http.ZokeParams;
import com.zoke.support.image.activity.GalleryActivity;
import com.zoke.support.image.activity.GalleryActivity.HandleType;
import com.zoke.support.image.activity.GalleryActivity.PhotoRequestCode;
import com.zoke.support.image.activity.ImageCutActivity;
import com.zoke.support.utils.FileUtil;
import com.zoke.support.utils.LogUtil;
import com.zoke.support.utils.MessageHandlerList;
import com.zoke.support.view.ZokeToast;

/**
 * 补全信息界面
 * 
 * @author jack
 * 
 */
public class Completion extends BaseUi {
	private AppDialog mSexDialog;
	private TextView mSexTv;
	private TextView mPosionTv;
	private ImageView mHeadIv;

	private File mPhotoFile;

	private String mTakePhotoPath;
	private EditText mNameEt;
	private EditText mPhoneEt;

	private String mName;
	private String mPhoneNumber;
	private int mSex;// 1代表男 2代表女
	private int mIdentity;// 1乘客 2车主
	private String mChanel;
	private String mOpenId;

	public static final String CHANELKEY = "_chanelKey";
	public static final String OPENIDKEY = "_openIdkey";

	private AppLoadingDialog mLoadinDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_completion);
		mTitleManager.setTitle("补全信息").setLeftIcon(R.drawable.title_back);
		mEnableSwipeRight = true;
		mLoadinDialog = new AppLoadingDialog(this, "正在注册中……");
		mChanel = getIntent().getStringExtra(CHANELKEY);
		mOpenId = getIntent().getStringExtra(OPENIDKEY);
		mTakePhotoPath = PathStores.getCachePath(getApplicationContext());
		findView();
	}

	/** 验证参数 true 代表通过 **/
	private boolean volidParams() {
		mName = mNameEt.getText().toString().trim();
		mPhoneNumber = mPhoneEt.getText().toString().trim();
		if (mPhotoFile == null) {
			ZokeToast.show(getApplicationContext(), "头像不能为空哦");
			return false;
		}

		if (TextUtils.isEmpty(mName)) {
			mNameEt.setError("用户名不能为空");
			return false;
		}

		if (TextUtils.isEmpty(mPhoneNumber)) {
			mPhoneEt.setError("电话不能为空");
			return false;
		}

		if (mSex == 0) {
			ZokeToast.show(getApplicationContext(), "请您选择性别");
			return false;
		}

		if (mIdentity == 0) {
			ZokeToast.show(getApplicationContext(), "请您选择身份");
			return false;
		}

		return true;
	}

	/** 补全信息 **/
	private void fetchCompletion() {
		// 做验证
		if (!volidParams())
			return;
		mLoadinDialog.show();
		ZokeParams param = CarpoolParamStore.getDefaultParam(mHashCode);
		param.setUrl(UrlBank.doCompletion);
		try {
			param.put("photoFile", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		param.put("name", mName);
		param.put("mobile", mPhoneNumber);
		param.put("sex", mSex + "");
		param.put("identity", mIdentity + "");
		param.put("channel", mChanel);
		param.put("openId", mOpenId);
		HttpStores.getInstense(getApplicationContext()).find(param);
	}

	@Override
	protected void findView() {
		mSexTv = (TextView) findViewById(R.id.edit_item_tv_sex);
		mPosionTv = (TextView) findViewById(R.id.completion_tv);
		mHeadIv = (ImageView) findViewById(R.id.completion_head_iv);
		// Name
		mNameEt = (EditText) findViewById(R.id.edit_item_tv_username);
		// phone
		mPhoneEt = (EditText) findViewById(R.id.completion_phoneEt);
	}

	@Override
	public void onSuccess(ZokeParams out) {
		super.onSuccess(out);
		String result = (String) out.getResult();
		ZokeToast.show(getApplicationContext(), "" + result);
		mLoadinDialog.dismiss();
		try {
			handleResult(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理结果
	 * 
	 * @throws JSONException
	 **/
	private void handleResult(String result) throws JSONException {
		JSONObject jo = new JSONObject(result);
		String code = jo.optString("code");
		if ("0".equals(code)) {
			// 非首次登陆 直接跳转到首页
			LogUtil.e("result==" + result);
			UserBeen userBeen = new UserBeen();
			JSONObject joo = jo.getJSONObject("result");
			userBeen.setIdentify(joo.optString("identity"));
			userBeen.setPhone(joo.optString("mobile"));
			userBeen.setUserName(joo.optString("name"));
			userBeen.setSex(joo.optString("sex"));
			userBeen.setPhone(CarpoolConfig.HTTPURL + joo.optString("photo"));
			userBeen.setUserId(joo.optString("sid"));
			// -- 完成注册 跳转
			MessageHandlerList.sendMessage(Login.class,
					ZokeConfig.ALL_UI_FINISH);
			this.onBackPressed();
			mIntent = new Intent(this, Main.class);
			startUI(mIntent);
			return;
		}
	}

	@Override
	public void onFails(ZokeParams out) {
		super.onFails(out);
		ZokeErro erro = (ZokeErro) out.getResult();
		ZokeToast.show(getApplicationContext(), "注册失败，请重试" + erro.getErrorNo());
		mLoadinDialog.dismiss();
	}

	/** 马上体验--下一步关注频道列表 无论选择与否默认关注第一个 **/
	public void onClickOk(View view) {
		// 进入提交
		fetchCompletion();
	}

	/** 性別点击 **/
	public void onClickSex(View view) {
		mSexDialog = new AppDialog(Completion.this);
		mSexDialog.setDialogTitle("设置性别");
		mSexDialog.setchoseView(new ChoseItemClick() {
			@Override
			public void onItemClick(int position, View view) {
				mSexTv.setText(position == 0 ? "男" : "女");
				mSex = position == 0 ? 1 : 2;
			}
		});
		mSexDialog.setChoseFirstText("男");
		mSexDialog.setChoseSecText("女");
		mSexDialog.show();
	}

	/** 身份 **/
	public void onClickSf(View view) {
		mSexDialog = new AppDialog(Completion.this);
		mSexDialog.setDialogTitle("设置身份");
		mSexDialog.setchoseView(new ChoseItemClick() {
			@Override
			public void onItemClick(int position, View view) {
				mPosionTv.setText(position == 0 ? "我是乘客" : "我是车主");
				mIdentity = position == 0 ? 1 : 2;
			}
		});
		mSexDialog.setChoseFirstText("我是乘客");
		mSexDialog.setChoseSecText("我是车主");
		mSexDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PhotoRequestCode.CROP) {
			// 裁减
			if (data == null)
				return;
			String path = data.getStringExtra(PhotoRequestCode.REQUESTKEY);
			mPhotoFile = new File(path);
			// 显示Head
			path = "file://" + path;
			ImageLoader.getInstance().displayImage(path, mHeadIv,
					ImageConfig.getHeadOptions());
			return;
		}

		if (requestCode == 1) {
			// 拍照
			// 拍照返回的图片过大 需要压缩到100kb
			Bitmap bit = FileUtil.compressBitmap(mTakePhotoPath, 100);
			if (bit == null)
				return;
			String newFilePath = FileUtil.BitmapToFile(bit,
					PathStores.getCachePath(Completion.this));
			mIntent = new Intent();
			mIntent.setClass(getApplicationContext(), ImageCutActivity.class);
			mIntent.putExtra(ImageCutActivity.CUTIMAGEPATH, newFilePath);
			startUIForResult(mIntent, PhotoRequestCode.CROP);
			return;
		}

	}

	/** 头像 **/
	public void onClickHead(View view) {
		mSexDialog = new AppDialog(Completion.this);
		mSexDialog.setDialogTitle("设置头像");
		mSexDialog.setchoseView(new ChoseItemClick() {
			@Override
			public void onItemClick(int position, View view) {
				if (position == 0) {
					mTakePhotoPath = FileUtil.takePicture(Completion.this,
							mTakePhotoPath);
					return;
				}
				if (position == 1) {
					mIntent.setClass(Completion.this, GalleryActivity.class);
					mIntent.putExtra(GalleryActivity.HANDLETYPE,
							HandleType.CROP);
					startUIForResult(mIntent, PhotoRequestCode.CROP);
					return;
				}
			}
		});
		mSexDialog.setChoseFirstText("拍照");
		mSexDialog.setChoseSecText("相册");
		mSexDialog.show();
	}
}
